package com.ruoyi.finance.controller;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.ruoyi.finance.config.AlipayConfig;
import com.ruoyi.finance.domain.TCwPaymentPlan;
import com.ruoyi.finance.service.ITCwPaymentPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.servlet.ModelAndView;

/**
 * 【请填写功能名称】Controller
 * 
 * @author wish
 * @date 2021-06-22
 */
@RestController
@RequestMapping("/pay")
public class TCwPaymentPlanController extends BaseController
{
    @Autowired
    private ITCwPaymentPlanService tCwPaymentPlanService;


    @PreAuthorize(hasPermi = "finance:pay:billList")
    @GetMapping("/billList")
    public TableDataInfo billList(TCwPaymentPlan tCwPaymentPlan){
        startPage();
        List<TCwPaymentPlan> billList=tCwPaymentPlanService.billList(tCwPaymentPlan);
        return getDataTable(billList);
    }
    @PreAuthorize(hasPermi = "finance:pay:findList")
    @GetMapping("/findList")
    public TableDataInfo findList(TCwPaymentPlan tCwPaymentPlan){
        startPage();
        List<TCwPaymentPlan> findList=tCwPaymentPlanService.findList(tCwPaymentPlan);
        return getDataTable(findList);
    }

    @PreAuthorize(hasPermi = "finance:pay:findAll")
    @GetMapping("/findAll")
    public TableDataInfo findAll(TCwPaymentPlan tCwPaymentPlan){
        startPage();
        List<TCwPaymentPlan> findAll=tCwPaymentPlanService.findAll(tCwPaymentPlan);
        return getDataTable(findAll);
    }

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize(hasPermi = "finance:pay:list")
    @GetMapping("/list")
    public TableDataInfo list(TCwPaymentPlan tCwPaymentPlan)
    {
        startPage();
        List<TCwPaymentPlan> list = tCwPaymentPlanService.selectTCwPaymentPlanList(tCwPaymentPlan);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize(hasPermi = "finance:pay:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TCwPaymentPlan tCwPaymentPlan) throws IOException
    {
        List<TCwPaymentPlan> list = tCwPaymentPlanService.selectTCwPaymentPlanList(tCwPaymentPlan);
        ExcelUtil<TCwPaymentPlan> util = new ExcelUtil<TCwPaymentPlan>(TCwPaymentPlan.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize(hasPermi = "finance:pay:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tCwPaymentPlanService.selectTCwPaymentPlanById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize(hasPermi = "finance:pay:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TCwPaymentPlan tCwPaymentPlan)
    {
        return toAjax(tCwPaymentPlanService.insertTCwPaymentPlan(tCwPaymentPlan));
    }

    /**
     * 【请填写功能名称】
     */
    @PreAuthorize(hasPermi = "finance:pay:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TCwPaymentPlan tCwPaymentPlan)
    {
        return toAjax(tCwPaymentPlanService.updateTCwPaymentPlan(tCwPaymentPlan));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize(hasPermi = "finance:pay:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tCwPaymentPlanService.deleteTCwPaymentPlanByIds(ids));
    }

    @PreAuthorize(hasPermi = "finance:pay:payList")
    @GetMapping("/payList")
    public void pay(HttpServletRequest req, ModelAndView modelAndView, HttpServletResponse rep) throws AlipayApiException, IOException {

        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = UUID.randomUUID().toString().replace("-","");
        //付款金额，必填  (随机生成 0-1000)
        String total_amount =String.valueOf(Math.floor(Math.random() * 1000+1));
        //订单名称，必填
        String subject = "订单名称";
        //商品描述，可空
        String body = "特价苹果";

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();

        rep.setContentType("text/html;charset=" + AlipayConfig.charset);
        rep.getWriter().write(result);//直接将完整的表单html输出到页面
        rep.getWriter().flush();
        rep.getWriter().close();

    }



    /**
     * 回调路径return_url
     * @param request
     * @param response
     * @throws AlipayApiException
     * @throws
     */
    @RequestMapping("return_url.view")
    @ResponseBody
    public String returnUrl(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, UnsupportedEncodingException, UnsupportedEncodingException {

        System.out.println("调用 同步 回调");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type);
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            request.setAttribute("out_trade_no", out_trade_no);
            request.setAttribute("trade_no", trade_no);
            request.setAttribute("total_amount", total_amount);


            System.out.println("订单处理：系统订单号" + out_trade_no + "支付宝交易号：" + trade_no);
            //系统处理根据支付宝回调更改订单状态或者其他关联表的数据
          /*  OrderInfo order = payService.findOneByTradeCode(out_trade_no);
            if(order == null){
                signVerified = false;
                request.setAttribute("signVerified", signVerified);
                request.setAttribute("reason", "商户订单号不存在");
                System.out.println("系统订单："+ out_trade_no + "不存在。");
            }else{
                if(!order.getMoney().toString().equals(total_amount)){
                    signVerified = false;
                    request.setAttribute("signVerified", signVerified);
                    request.setAttribute("reason", "付款金额不对");
                    return "notify_url";
                }
                if(order.getTradeStatus() == 1){//判断当前订单是否已处理，避免重复处理
                    log.info("系统订单："+ out_trade_no + "无需重复处理。");
                }else{
                    order.setTradeStatus(1);//修改订单状态为已支付
                    Date payedAt = new Date();
                    order.setTransactionId(trade_no);
                    order.setPayedAt(payedAt);
                    payService.payOrder(order);
                    System.out.println("系统订单："+ out_trade_no + "成功支付。");
                }
            }
*/
        }else{
            request.setAttribute("reason", "验签失败");
        }
        request.setAttribute("signVerified", signVerified);
        return "return_url";
    }


    /**
     * 异步回调路径 notify_url
     * @param request
     * @param response
     * @throws AlipayApiException
     * @throws
     */
    @RequestMapping("notify_url.view")
    public void notify_url(HttpServletRequest request, HttpServletResponse response) throws AlipayApiException, IOException {

        System.out.println("调用 异步 回调");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset,AlipayConfig.sign_type);
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            request.setAttribute("out_trade_no", out_trade_no);
            request.setAttribute("trade_no", trade_no);
            request.setAttribute("total_amount", total_amount);


            System.out.println("订单处理：系统订单号" + out_trade_no + "支付宝交易号：" + trade_no);
            //系统处理根据支付宝回调更改订单状态或者其他关联表的数据
          /*  OrderInfo order = payService.findOneByTradeCode(out_trade_no);
            if(order == null){
                signVerified = false;
                request.setAttribute("signVerified", signVerified);
                request.setAttribute("reason", "商户订单号不存在");
                System.out.println("系统订单："+ out_trade_no + "不存在。");
            }else{
                if(!order.getMoney().toString().equals(total_amount)){
                    signVerified = false;
                    request.setAttribute("signVerified", signVerified);
                    request.setAttribute("reason", "付款金额不对");
                    return "notify_url";
                }
                if(order.getTradeStatus() == 1){//判断当前订单是否已处理，避免重复处理
                    log.info("系统订单："+ out_trade_no + "无需重复处理。");
                }else{
                    order.setTradeStatus(1);//修改订单状态为已支付
                    Date payedAt = new Date();
                    order.setTransactionId(trade_no);
                    order.setPayedAt(payedAt);
                    payService.payOrder(order);
                    System.out.println("系统订单："+ out_trade_no + "成功支付。");
                }
            }
*/
        }else{
            request.setAttribute("reason", "验签失败");
        }
        request.setAttribute("signVerified", signVerified);


        response.setContentType("text/html;charset=" + AlipayConfig.charset);
        response.getWriter().write("success");//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();




    }
}
